package com.krain.meijusky.activity;

import android.animation.LayoutTransition;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.krain.corelibrary.util.DeviceInfo;
import com.krain.corelibrary.util.ImageLorder;
import com.krain.corelibrary.util.SpUtil;
import com.krain.corelibrary.widget.loadingView.LoadingView;
import com.krain.corelibrary.widget.silderview.Animations.ChildAnimationExample;
import com.krain.corelibrary.widget.silderview.SliderLayout;
import com.krain.corelibrary.widget.silderview.SliderTypes.BaseSliderView;
import com.krain.corelibrary.widget.silderview.SliderTypes.TextSliderView;
import com.krain.meijusky.R;
import com.krain.meijusky.constant.SpKeys;
import com.krain.meijusky.entity.ResourceEntity;
import com.umeng.update.UmengUpdateAgent;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

@EActivity(R.layout.activity_main)
public class MainActivity extends BaseActivity {
    Document document;
    List<ResourceEntity> mHotList;

    @ViewById(R.id.slider)
    SliderLayout mSliderLayout;
    @ViewById(R.id.act_main_drawLayout)
    DrawerLayout mDrawLayout;
    private ActionBarDrawerToggle mDrawerToggle;
    @ViewById(R.id.act_main_category1_grid)
    GridLayout grid_category1;
    @ViewById(R.id.act_main_category2_grid)
    GridLayout grid_category2;
    @ViewById(R.id.act_main_category3_grid)
    GridLayout grid_category3;
    @ViewById(R.id.act_main_category4_grid)
    GridLayout grid_category4;
    @ViewById(R.id.act_main_nav_view)
    NavigationView mNaview;
    @ViewById(R.id.loadView)
    LoadingView mLoadingView;
    List<ResourceEntity> ent_evolutions, ent_terrors, ent_citys, ent_crimes;
    Elements evolutions, terrors, citys, crimes;
    SearchView searchView;

    @AfterViews
    void afterView() {
        mDrawLayout.setVisibility(View.GONE);
        mHotList = new ArrayList<>();
        getMainMsgFromNetWork();
        getSupportActionBar().setHomeButtonEnabled(true);
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawLayout, mToolBar, R.string.app_name, R.string.app_name) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }
        };
        mDrawerToggle.syncState();
        mDrawLayout.setDrawerListener(mDrawerToggle);
        mNaview.setNavigationItemSelectedListener(navigationLisener);
    }


    /**
     * 抽屉栏开关的回调
     */
    NavigationView.OnNavigationItemSelectedListener navigationLisener = new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            mDrawLayout.closeDrawers();
            switch (menuItem.getItemId()) {
                case R.id.nav_since:
                    CategoryListActivity.jumpTothisActivity(mContext, getString(R.string.category_kehuan), getString(R.string.category_key_kehuan));
                    break;
                case R.id.nav_magic:
                    CategoryListActivity.jumpTothisActivity(mContext, getString(R.string.category_lingyi), getString(R.string.category_key_lingyi));
                    break;
                case R.id.nav_city:
                    CategoryListActivity.jumpTothisActivity(mContext, getString(R.string.category_dushi), getString(R.string.category_key_dushi));
                    break;
                case R.id.nav_crime:
                    CategoryListActivity.jumpTothisActivity(mContext, getString(R.string.category_fanzui), getString(R.string.category_key_fanzui));
                    break;
                case R.id.nav_xuanxiu:
                    CategoryListActivity.jumpTothisActivity(mContext, getString(R.string.category_xuanxiu), getString(R.string.category_key_xuanxiu));
                    break;
                case R.id.nav_dongman:
                    CategoryListActivity.jumpTothisActivity(mContext, getString(R.string.category_dongman), getString(R.string.category_key_dongman));
                    break;
            }
            return false;
        }
    };

    /**
     * 获取首页推荐
     */
    @Background
    void getMainMsgFromNetWork() {
        try {
            document = Jsoup.connect("http://www.meijutt.com/").get();
            SpUtil.getInstance(mContext).putString(SpKeys.KEY_BASEURI_MEIJUTT, document.baseUri());
            Elements hotOfToday = document.select("ul[id=hot1]");//今日热门的所有HTML内容
            Elements secondCategorys = document.select("div[class=c1_l_wap_contact]");//获取四大分类的数据
            Elements listHot = hotOfToday.select("li");
            setHotOfToday(listHot);
            setSecondCategory(secondCategorys);
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("huyamin", "e=" + e.toString());
            baseUtil.showSnackBar(this, "网络返回异常，请检查您的网络");
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        UmengUpdateAgent.update(this);
    }

    /**
     * 设置二级分类的方法
     *
     * @param secondCategorys
     */
    @UiThread(propagation = UiThread.Propagation.REUSE)
    void setSecondCategory(Elements secondCategorys) {
        if (secondCategorys.size() < 4) {
            baseUtil.showSnackBar(this, "获取分类列表出错");
            return;
        }
        evolutions = secondCategorys.get(0).select("a[class=aimg]");//科幻数据
        terrors = secondCategorys.get(1).select("a[class=aimg]");//恐怖数据
        citys = secondCategorys.get(2).select("a[class=aimg]");//都市数据
        crimes = secondCategorys.get(3).select("a[class=aimg]");//犯罪数据
        setSencondCateGoryGridlayout(grid_category1, evolutions);
        setSencondCateGoryGridlayout(grid_category2, terrors);
        setSencondCateGoryGridlayout(grid_category3, citys);
        setSencondCateGoryGridlayout(grid_category4, crimes);
        setGridlayoutItemClick(grid_category1, ent_evolutions);
        setGridlayoutItemClick(grid_category2, ent_terrors);
        setGridlayoutItemClick(grid_category3, ent_citys);
        setGridlayoutItemClick(grid_category4, ent_crimes);
        mLoadingView.showContentView(mDrawLayout);
    }

    /**
     * 设置Gridlayout的item点击事件
     *
     * @param gridlaout
     */
    void setGridlayoutItemClick(final GridLayout gridlaout, final List<ResourceEntity> entitys) {
        for (int i = 0; i < gridlaout.getChildCount(); i++) {
            final int j = i;
            gridlaout.getChildAt(i).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    DetailActivity.jumpTothisActivity(mContext, entitys.get(j), ((LinearLayout) gridlaout.getChildAt(j)).getChildAt(0));
                }
            });
        }
    }


    private final int TAGSPACEPADDING = 20;
    int tagWidth = 0;
    private int widthPixels = 0;

    /**
     * 设置gridlayout的数据
     *
     * @param grid
     * @param elements
     */
    void setSencondCateGoryGridlayout(GridLayout grid, Elements elements) {
        widthPixels = DeviceInfo.getScreenDisplay(this).widthPixels;
        List<ResourceEntity> entitys = new ArrayList<>();
        for (int i = 0; i < elements.size(); i++) {
            ResourceEntity entity = new ResourceEntity();
            String simg = elements.get(i).select("img[alt]").attr("src");
            String sNextUrl = elements.get(i).attr("href");
            String sTitle = elements.get(i).select("img[alt]").attr("alt");
            GridLayout.Spec rowSpec = GridLayout.spec(i / 3);
            GridLayout.Spec columnSpec = GridLayout.spec(i % 3);
            GridLayout.LayoutParams params = new GridLayout.LayoutParams(rowSpec, columnSpec);
            params.setMargins(TAGSPACEPADDING, TAGSPACEPADDING, TAGSPACEPADDING, TAGSPACEPADDING);
            ViewGroup viewGroup = (ViewGroup) grid.getParent();
            tagWidth = widthPixels - (viewGroup.getPaddingLeft() + viewGroup.getPaddingRight()) - TAGSPACEPADDING * (grid.getColumnCount() * 2);
            params.width = tagWidth / grid.getColumnCount();
            View view = LayoutInflater.from(this).inflate(R.layout.item_mian_gridlayout, null);
            ImageView img = (ImageView) view.findViewById(R.id.item_main_gridlayout_img);
            TextView text = (TextView) view.findViewById(R.id.item_main_gridlayout_bottom_text);
            ImageLorder.getInstance(this).loadImage(this, img, simg);
            text.setText(sTitle);
            grid.addView(view, params);
            entity.setNextUrl(sNextUrl);
            entity.setTitle(sTitle);
            entity.setImg(simg);
            entitys.add(entity);
            if (elements == evolutions)
                ent_evolutions = entitys;
            else if (elements == terrors)
                ent_terrors = entitys;
            else if (elements == citys)
                ent_citys = entitys;
            else ent_crimes = entitys;
        }

    }


    /**
     * 设置今日热门
     */
    @UiThread(propagation = UiThread.Propagation.REUSE)
    void setHotOfToday(Elements listHot) {
        for (Element el : listHot) {
            TextSliderView textSliderView = new TextSliderView(this);
            ResourceEntity entity = new ResourceEntity();
            entity.setImg(el.select("img[alt]").attr("src"));
            entity.setTitle(el.select("img[alt]").attr("alt"));
            entity.setNextUrl(el.baseUri() + el.select("a[href]").attr("href"));
            textSliderView.description(entity.getTitle())
                    .image(entity.getImg())
                    .setScaleType(BaseSliderView.ScaleType.Fit)
                    .setMessage(entity)
                    .setOnSliderClickListener(mHotToadyClickListener);
            mSliderLayout.addSlider(textSliderView);
        }
        mSliderLayout.setCustomAnimation(new ChildAnimationExample());
        mSliderLayout.setPresetTransformer(SliderLayout.Transformer.ZoomOut);
        mSliderLayout.setPresetIndicator(SliderLayout.PresetIndicators.Right_Bottom);
        mSliderLayout.setDuration(3000);
//        mSliderLayout.addOnPageChangeListener(this);

    }


    @Override
    protected String getToolbarTitle() {
        return getString(R.string.title_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        MenuItem item = menu.findItem(R.id.action_search);
        searchView = (SearchView) MenuItemCompat.getActionView(item);
        searchView.setSubmitButtonEnabled(true);
        ImageView imageView = (ImageView) searchView.findViewById(R.id.search_go_btn);
        imageView.setImageDrawable(this.getResources().getDrawable(R.mipmap.ic_search));
        searchView.setQueryHint(getString(R.string.search_hint));
        searchView.setOnQueryTextListener(onQueryTextListener);
        LinearLayout searchBar = (LinearLayout) searchView.findViewById(R.id.search_bar);
        searchBar.setLayoutTransition(new LayoutTransition());

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        return true;
    }


    /**
     * 搜索的回调事件
     */
    android.support.v7.widget.SearchView.OnQueryTextListener onQueryTextListener = new android.support.v7.widget.SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            SearchResultActivity.jumpTothisActivity(mContext, query);
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            return false;
        }
    };


    /**
     * 今日热门的点击事件
     */
    BaseSliderView.OnSliderClickListener mHotToadyClickListener = new BaseSliderView.OnSliderClickListener() {
        @Override
        public void onSliderClick(BaseSliderView slider) {
            DetailActivity.jumpTothisActivity(mContext, (ResourceEntity) slider.getMessage(), mSliderLayout.getChildAt(0));
        }
    };
}
